package bo.gustavo.scrapper.export;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.supercsv.cellprocessor.FmtBool;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;

import bo.gustavo.scrapper.model.AppData;
import bo.gustavo.scrapper.model.Persister;
import bo.gustavo.scrapper.util.DataBaseAccessType;

public class CSVExporter {

	public static void exportToCSV(String path) {
		List<AppData> appDataList = Persister.getInstance().maskOperations(AppData.class, null, DataBaseAccessType.QUERY);
		ICsvBeanWriter beanWriter = null;
		try {
			beanWriter = new CsvBeanWriter(new FileWriter(path), CsvPreference.STANDARD_PREFERENCE);

			final String[] header = new String[] { "title", "developerName", "developerWebsite", "appURL", "reviewAmount", "developerEmail",
					"category", "paid" };
			final CellProcessor[] processors = getProcessors();

			beanWriter.writeHeader(header);
			for (final AppData appData : appDataList) {
				beanWriter.write(appData, header, processors);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (beanWriter != null) {
				try {
					beanWriter.close();
				} catch (IOException e) {
				}
			}
		}

	}

	private static CellProcessor[] getProcessors() {

		final CellProcessor[] processors = new CellProcessor[] { new Optional(), new Optional(), new Optional(), new Optional(), new Optional(),
				new Optional(), new Optional(), new Optional(new FmtBool("Y", "N")) };

		return processors;
	}

}
